package post

import (
	"context"
	"github.com/fatih/color"
	"github.com/ifnk/micro-blog/internal/pkg/dbcontext"
	"github.com/ifnk/micro-blog/internal/pkg/log"
	"github.com/ifnk/micro-blog/protobuf/post_pb"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

func NewPostServer(logger *log.Logger, db *dbcontext.GormDB, jinzhuDB *dbcontext.JinZhuDB) Server {
	return Server{
		logger:                   logger,
		db:                       db,
		PostServiceDefaultServer: post_pb.PostServiceDefaultServer{DB: jinzhuDB.DB},
	}
}

type Server struct {
	post_pb.PostServiceDefaultServer
	logger *log.Logger
	db     *dbcontext.GormDB
}

func (s Server) IncrementCommentCount(ctx context.Context, req *post_pb.IncrementCommentCountRequest) (*post_pb.IncrementCommentCountResponse, error) {
	postID := req.GetId()
	p := post_pb.PostORM{}
	err := s.db.First(&p, postID).Error
	if err != nil {
		color.Blue("err.Error -> %+v", err.Error)
		return nil, status.Errorf(codes.NotFound, "post %d not found", postID)
	}
	p.CommentCount++

	err = s.db.Save(&p).Error
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to update post %d", postID)
	}

	return &post_pb.IncrementCommentCountResponse{Success: true}, nil
}

func (s Server) IncrementCommentCountCompensate(ctx context.Context, req *post_pb.IncrementCommentCountRequest) (*post_pb.IncrementCommentCountResponse, error) {
	postID := req.GetId()
	p := &post_pb.PostORM{}
	err := s.db.First(&p, postID).Error
	if err != nil {
		return nil, status.Errorf(codes.NotFound, "post %d not found", postID)
	}
	p.CommentCount--
	err = s.db.Save(&p).Error
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to update post %d", postID)
	}
	return &post_pb.IncrementCommentCountResponse{Success: true}, nil
}
